package com.globefrog.framework.web;

import com.globefrog.framework.log.util.ReadOnly;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;

/**
 * 请求上下文.
 *
 * @author : caijinbang
 * @date : Create in 2021-01-16
 */

public class RequestContextServiceImpl implements RequestContextService {

  private final ReadOnly<HttpServletRequest> request = new ReadOnly<>();
  private final ReadOnly<String> clientId = new ReadOnly<>();
  private final ReadOnly<String> requestId = new ReadOnly<>();
  private final ReadOnly<Date> requestDate = new ReadOnly<>();
  private final ReadOnly<String> action = new ReadOnly<>();

  public RequestContextServiceImpl() {
  }

  /**
   * @return
   */
  public String getClientRequestedFullUrlWithQueryString() {

    // TODO
    return null;
  }

  /**
   * @return
   */
  public String getClientRequestedRelativeUrlWithQueryString() {
    // TODO
    return null;
  }

  public String getClientRequestedRelativeUrl() {
    // TODO
    return null;
  }

  public String getClientRequestServerName() {
    return ((HttpServletRequest) this.request.value()).getServerName();
  }

  public boolean isSecure() {
    return ((HttpServletRequest) this.request.value()).isSecure();
  }

  public String getRemoteAddress() {
    HttpServletRequest httpServletRequest = request.value();
    // 获取客户端IP请求头
    String clientIpHeader = httpServletRequest.getHeader("client-ip");
    // Http请求端真实的IP请求头
    String xForwardedFor = httpServletRequest.getHeader("x-forwarded-for");
    return StringUtils.hasText(clientIpHeader) ? clientIpHeader : xForwardedFor;
  }

  public String getClientId() {
    return this.clientId.value();
  }

  public String getRequestId() {
    return this.requestId.value();
  }

  public Date getRequestDate() {
    return this.requestDate.value();
  }

  public String getAction() {
    return this.action.value();
  }

  public String getRequestHeader(String name) {
    return (this.request.value()).getHeader(name);
  }

  public void setClientId(String clientId) {
    this.clientId.set(clientId);
  }

  public void setRequestId(String requestId) {
    this.requestId.set(requestId);
  }

  public void setRequestDate(Date requestDate) {
    this.requestDate.set(requestDate);
  }

  public void setAction(String action) {
    this.action.set(action);
  }

  public void setHttpRequest(HttpServletRequest request) {
    this.request.set(request);
  }


  public String getQueryString() {
    //String query = this.requestURLHelper.getClientRequestedQueryString();
    //return query == null ? "" : query;
    return null;
  }
}
